<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\setting;

use app\common\model\Channel as ChannelModel;
use app\adminapi\controller\Base;

class Payment extends Base
{
    /**
     * @notes Payment gateway list
     * @auth true
     */
    public function list(ChannelModel $channelModel)
    {
        $res = $channelModel::paginate($this->limit);
        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * @notes Get code interface list
     */
    private function codeList($type)
    {
        $path        = app_path() . '/api/' . $type . '/';
        $directories = new \RecursiveDirectoryIterator($path);
        $iterator    = new \RecursiveIteratorIterator($directories);
        $phpFiles    = new \RegexIterator($iterator, '/\w+\.php$/', \RecursiveRegexIterator::GET_MATCH);
        $data        = [];
        foreach ($phpFiles as $phpFile) {
            // Skip if file path contains 'interfaces'
            if (strpos($phpFile[0], 'Interface') !== false) {
                continue;
            }
            $content = file_get_contents($path . $phpFile[0]);
            // Get remark from content
            preg_match('/@note\s(.*)/', $content, $remark);
            preg_match('/@field  params\s(.*)/', $content, $fields);
            $fileName = str_replace('.php', '', $phpFile[0]);
            $data[]   = [
                'label'  => $fileName . ' ( ' . $remark[1] . ' ) ',
                'value'  => $fileName,
                'remark' => $remark[1] ?? '',
                'fields' => $fields[1] ?? '',
            ];
        }
        return $data;
    }

    /**
     * All interface code names
     * @auth false
     */
    public function code()
    {
        $type = inputs('type', 'collection');
        $data = $this->codeList($type);

        $this->success('', $data);
    }

    /**
     * Payment gateway label value
     * @auth false
     */
    public function listSimple()
    {
        $res = ChannelModel::field('id as value,title as label')->order('sort asc')->select()->toArray();

        $this->success('', $res);
    }

    /**
     * @notes Gateway details
     * @auth false
     */
    public function detail()
    {
        $id   = inputs('id/d', 0);
        $data = ChannelModel::where(['id' => $id])->find();

        $this->success('', $data);
    }

    /**
     * @notes Delete gateway
     * @auth true
     */
    public function del()
    {
        $id  = inputs('id/d', 0);
        $res = ChannelModel::destroy($id);

        return $res ? $this->success() : $this->error();
    }

    /**
     * POST data validation
     */
    private function postData()
    {
        $data = [
            'id'             => inputs('id/d', ''),
            'title'          => inputs('title'),
            'status'         => inputs('status'),
            'show_name'      => inputs('show_name'),
            'is_available'   => inputs('is_available'),
            'sort'           => inputs('sort'),
            'type'           => inputs('type'),
            'code'           => inputs('code'),
            'account_fields' => inputs('account_fields'),
            'paytype'        => inputs('paytype'),
        ];

        $validate = new \app\adminapi\validate\setting\CollectionValidate;
        $validate->scene('collection')->failException(true)->check($data);

        $codeType = inputs('codeType', 'collection');
        $codeList = array_column($this->codeList($codeType), 'value');

        !in_array($data['code'], $codeList) && throw new \Exception(trans('interface_file_not_exists', [], 'collection'));

        return $data;
    }

    /**
     * @notes Add gateway
     * @auth true
     */
    public function add()
    {
        $data = array_diff_key($this->postData(), ['id']);
        /** @var ChannelModel  $res */
        $res       = ChannelModel::create($data);
        $res->sort = $res->id;
        $res->save();

        return $res ? $this->success() : $this->error();
    }

    /**
     * @notes Edit gateway
     * @auth true
     */
    public function edit()
    {
        $data = $this->postData();
        $res  = ChannelModel::update($data);

        return $res ? $this->success() : $this->error();
    }
}